package cn.gotom.core.web.action;


import java.util.ArrayList;
import java.util.List;

import cn.gotom.coding.EncodingUtils;
import cn.gotom.core.pojos.Right;
import cn.gotom.core.pojos.Role;
import cn.gotom.core.pojos.User;
import cn.gotom.core.service.RightService;
import cn.gotom.core.service.UserService;
import cn.gotom.core.vo.Menu;
import cn.gotom.core.web.Constants;

import com.google.inject.Inject;

public class MenuAction extends SupportAction
{

	public String execute() throws Exception
	{
		User user = (User) this.getSession().get(Constants.USER_SESSION_KEY);
		if (user != null)
		{
			List<Right> rightList = rightService.findAll();
			for (Right r : rightList)
			{
				EncodingUtils.encoding(r, "cp850", "GBK");
			}			
			if (User.administrator.equalsIgnoreCase(user.getUsername()))
			{
				this.setShowMenu(false);
				for (Right right : rightList)
				{
					right.setChecked(true);
				}
			}
			else
			{
				user = userService.get(user.getId());
				for (Role role : user.getRoles())
				{
					for (Right o : role.getRights())
					{
						for (Right right : rightList)
						{
							if (right.equals(o))
							{
								right.setChecked(true);
							}
						}
					}
				}
			}
			for (Right right : rightList)
			{
				Menu find = null;
				for (Menu m : menuList)
				{
					if (right.getGroupName().equals(m.getGroupName()))
					{
						find = m;
						break;
					}
				}
				if (find == null)
				{
					find = new Menu();
					menuList.add(find);
				}
				find.setGroupName(right.getGroupName());
				find.getRightList().add(right);
			}
		}
		return Constants.SUCCESS;
	}

	private static final long serialVersionUID = 1L;

	@Inject
	private RightService rightService;

	@Inject
	private UserService userService;

	private List<Menu> menuList = new ArrayList<Menu>();
	
	/**
	 * 显示静太菜单
	 */
	private boolean showMenu = true;

	public List<Menu> getMenuList()
	{
		return menuList;
	}

	public void setMenuList(List<Menu> menuList)
	{
		this.menuList = menuList;
	}

	public boolean isShowMenu()
	{
		return showMenu;
	}

	public void setShowMenu(boolean showMenu)
	{
		this.showMenu = showMenu;
	}

	
}
